#include <iostream>

#include "mysocket.h"
#include "initsock.h"
#include "acceptConn.h"
#include "communication.h"

//上锁，用于线程同步，防止连接客户端线程和通信线程对主线程的readfds操作混乱
std::mutex mtx;

int main(void)
{
    //创建监听的套接字socket
    int lfd = 0;
    
    //初始化通信套接字lfd
    initsock(lfd);

    //等待客户端连接
    std::cout << "wait for client connect..." << std::endl;
    struct pollfd fds[1024];
    //初始化
    for(int i = 0; i<1024; i++)
    {
        fds[i].fd = -1;
        fds[i].events = POLLIN;
    }
    fds[0].fd = lfd;
    int maxfd = 0;    
    while(1)
    {
        std::cout << "poll wait..." << std::endl;
        int ret = poll(fds, maxfd+1, -1);
        if(ret == -1)
        {
            perror("poll---------------------");
            return -1;
        }

        //有新连接
        if(fds[0].revents & POLLIN)
        {
            std::thread t_accept(acceptConn , std::ref(maxfd),  std::ref(fds), std::ref(lfd));
            t_accept.detach();
        }

        //有新通信
        for(int i = 1; i <= maxfd; i++)
        {
            if(fds[i].revents & POLLIN)
            {
                //创建子线程处理读取到的数据
                std::thread t_communication(communication, std::ref(maxfd),  std::ref(fds),  std::ref(i));
                t_communication.detach(); 
            }
              
        }      
    }        
    
    close(lfd);
    
    return 0;
}